// 通用下载方法
import { blobValidate } from '@/utils/validate'
import ElMessage from 'autoprefixer/lib/utils'
import service from '@/utils/request'
import errorCode from '@/utils/errorCode'
import { saveAs } from 'file-saver';

// let downloadLoadingInstance

export default function useDownload(url, filename, config, method) {
  return service({
    url: url,
    method: method || 'get',
    responseType: 'blob',
    ...config
  }).then(async(res) => {

    const { data, headers } = res
    const isBlob = await blobValidate(data)
    if (isBlob) {
      const blob = new Blob([data])
      // const tempName = headers["content-disposition"].split(";")[1].split("filename=")[1];
      let contentDisposition = headers['content-disposition']
      let tempName = ''
      if (contentDisposition) {
        let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        let matches = filenameRegex.exec(contentDisposition)
        if (matches != null && matches[1]) {
          tempName = matches[1].split('\'\'')[1]
          tempName = decodeURIComponent(tempName) // 解码
        }
      }
      filename = (tempName && tempName != 'undefined') ? tempName : filename
      // console.log(filename, '========================', tempName === 'undefined', '"""--', contentDisposition);
      saveAs(blob, filename)
      // downloadLoadingInstance.close()
      return Promise.resolve()
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.message || errorCode['default']
      ElMessage.error(errMsg)
      // downloadLoadingInstance.close()
      return Promise.reject(new Error(errMsg))
    }

  }).catch((r) => {
    console.log('catch=====================')
    console.log(r.message)
    // ElMessage.error('下载文件出现错误，请联系管理员-！');
    // downloadLoadingInstance.close()
  })
}
